﻿using System;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;
using ExampleMvcApplication.Models.Request;
using ExampleMvcApplication.Models.Response;
using ExampleMvcApplication.Services;
using SmallMvc;

namespace ExampleMvcApplication.Controllers
{
    [HandleError]
    public class AccountController : Controller
    {
        private readonly IAuthenticationService _authenticationService;
        private readonly IMembershipService _membershipService;
        private readonly UrlResolver _urlResolver;

        public AccountController(IAuthenticationService authenticationService, IMembershipService membershipService, IHttpContextProvider httpContextProvider)
        {
            _authenticationService = authenticationService;
            _membershipService = membershipService;
            _urlResolver = new UrlResolver(httpContextProvider);
        }

        public ActionResult LogOn(string returnUrl)
        {
            return View(new LogOnRequest(returnUrl));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult LogOn(LogOnRequest request)
        {
            if (!ValidateLogOn(request.UserName, request.Password)) return View(request);
            return SignAndRedirectToUrlOrHome(request.UserName, request.RememberMe, request.ReturnUrl);
        }

        public ActionResult LogOff()
        {
            _authenticationService.SignOut();
            return RedirectHome();
        }

        public ActionResult Register(string returnUrl)
        {
            return View(new RegisterRequest(_membershipService.MinPasswordLength, returnUrl));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(RegisterRequest request)
        {
            if (ValidateRegistration(request.UserName, request.Email, request.Password, request.ConfirmPassword))
            {
                var createStatus = _membershipService.CreateUser(request.UserName, request.Password, request.Email);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    return SignAndRedirectToUrlOrHome(request.UserName, false, request.ReturnUrl);
                }
                ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
            }
            return View(request);
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View(new ChangePasswordRequest(User.Identity.Name, _membershipService.MinPasswordLength));
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangePassword(ChangePasswordRequest request)
        {
            if (!ValidateChangePassword(request.CurrentPassword, request.NewPassword, request.ConfirmPassword))
            {
                return View(request);
            }

            if (_membershipService.ChangePassword(User.Identity.Name, request.CurrentPassword, request.NewPassword))
            {
                return Redirect(_urlResolver.UrlFor<AccountController>(x=>x.ChangePassword()));
            }
            ModelState.AddModelError("_FORM", "The current password is incorrect or the new password is invalid.");
            return View(request);
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View(new MasterModel(Request.IsAuthenticated, User.Identity.Name));
        }

        private ActionResult RedirectHome()
        {
            return Redirect(_urlResolver.UrlFor<HomeController>(x => x.Index()));
        }

        private ActionResult SignAndRedirectToUrlOrHome(string userName, bool rememberMe, string urlOrNull)
        {
            _authenticationService.SignIn(userName, rememberMe);
            return !String.IsNullOrEmpty(urlOrNull) ? Redirect(urlOrNull) : RedirectHome();
        }

        #region Validation Methods

        private bool ValidateChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {
            if (String.IsNullOrEmpty(currentPassword))
            {
                ModelState.AddModelError("currentPassword", "You must specify a current password.");
            }
            if (newPassword == null || newPassword.Length < _membershipService.MinPasswordLength)
            {
                ModelState.AddModelError("newPassword",
                    String.Format(CultureInfo.CurrentCulture,
                         "You must specify a new password of {0} or more characters.",
                         _membershipService.MinPasswordLength));
            }

            if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal))
            {
                ModelState.AddModelError("_FORM", "The new password and confirmation password do not match.");
            }

            return ModelState.IsValid;
        }

        private bool ValidateLogOn(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("username", "You must specify a username.");
            }
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", "You must specify a password.");
            }
            if (!_membershipService.ValidateUser(userName, password))
            {
                ModelState.AddModelError("_FORM", "The username or password provided is incorrect.");
            }

            return ModelState.IsValid;
        }

        private bool ValidateRegistration(string userName, string email, string password, string confirmPassword)
        {
            if (String.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("username", "You must specify a username.");
            }
            if (String.IsNullOrEmpty(email))
            {
                ModelState.AddModelError("email", "You must specify an email address.");
            }
            if (password == null || password.Length < _membershipService.MinPasswordLength)
            {
                ModelState.AddModelError("password",
                    String.Format(CultureInfo.CurrentCulture,
                         "You must specify a password of {0} or more characters.",
                         _membershipService.MinPasswordLength));
            }
            if (!String.Equals(password, confirmPassword, StringComparison.Ordinal))
            {
                ModelState.AddModelError("_FORM", "The new password and confirmation password do not match.");
            }
            return ModelState.IsValid;
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }

}
